import React from "react";
import {SubMenuItemPropType, SubMenuItemStateType, MenuItemType} from './DataType'
import './index.css'
import {NavLink} from "react-router-dom";
import {CaretUpOutlined, CaretDownOutlined} from "@ant-design/icons"

export default class SubMenuItem extends React.Component<SubMenuItemPropType, SubMenuItemStateType> {
    state={
        collapsed:true,
        height: "0"
    }
    constructor(props:any) {
        super(props);
    }
    handelCollapsed=()=>{
        if(this.props.collapsed)
            this.state.height="0"
        else this.state.height="50px"
    }
    componentDidUpdate(prevProps: Readonly<SubMenuItemPropType>, prevState: Readonly<SubMenuItemStateType>, snapshot?: any) {
        this.handelCollapsed()
    }
    noChildren = () => {
        return (
            <NavLink to={this.props.MenuItem.path} className={'sub-menu-item'}>
                <div className={'icon'} style={{height: this.state.height}}>
                    {this.props.MenuItem.icon}
                </div>
                <div className={'title'} >
                    <span className={'title__text'}>
                       {this.props.MenuItem.name}
                    </span>
                </div>
            </NavLink>
        )
    }
    hasChildren = () => {
        return (
            <>
                <div className={'sub-menu-item'} onClick={this.handelCollapsed} style={{height: this.state.height}}>
                    <div className={'icon'}>
                        {this.props.MenuItem.icon}
                    </div>
                    <div className={'title'} >
                       <span className={'title__text'}>
                           {this.props.MenuItem.name}
                       </span>
                        <span>
                                {
                                    this.state.collapsed ? <CaretDownOutlined/> : <CaretUpOutlined/>
                                }
                       </span>
                    </div>
                </div>
                {
                    this.state.collapsed?<></>:
                        <div className={'children-list'}>
                            {
                                this.props.MenuItem.children.map((item: MenuItemType) => {
                                    return (
                                        <SubMenuItem MenuItem={item} collapsed={this.state.collapsed} key={item.path}/>
                                    )
                                })
                            }
                        </div>
                }

            </>
        )
    }
    render() {
        return (
            <>
                {
                    this.props.MenuItem.children.length===0?
                        this.noChildren():this.hasChildren()
                }
            </>
        );
    }
}